package com.wolfalpha.utron.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMContactManager;
import com.squareup.picasso.Picasso;
import com.wolfalpha.utron.R;
import com.wolfalpha.utron.activity.base.BaseNormalActivity;
import com.wolfalpha.utron.app.AppContext;
import com.wolfalpha.utron.bean.UserInfo;
import com.wolfalpha.utron.service.UserService;
import com.wolfalpha.utron.service.impl.UserServiceImpl;
import com.wolfalpha.utron.ui.UIHelper;
import com.wolfalpha.utron.utils.ThreadPoolUtils;
import com.wolfalpha.utron.view.AlertDialog;
import com.wolfalpha.utron.view.CircleImageView;
import com.wolfalpha.utron.view.EditAlertDialog;

import easemob.applib.controller.HXSDKHelper;
import easemob.chatuidemo.DemoHXSDKHelper;
import easemob.chatuidemo.activity.ChatActivity;
import easemob.chatuidemo.domain.User;
import easemob.chatuidemo.utils.UserUtils;

/**
 * 查看用户信息界面
 *
 * @author luodon
 */
public class UserInfoActivity extends BaseNormalActivity implements View.OnClickListener {

    private LinearLayout llIdea;            //他的想法
    private LinearLayout llProject;         //他的项目
    private LinearLayout llAddFriend;       //加好友
    private LinearLayout llAddAtention;     //加关注
    private LinearLayout llDetail;          //详细信息
    private LinearLayout llPartner;         //合伙人信息

    private CircleImageView ivHead;         //用户头像

    private ImageView ivChat;//对话

    private TextView tvName;                //用户昵称文字
    private TextView tvLevel;               //用户合伙人等级
    private TextView tvAttention;           //用户关注度

    private UserService userService;

    private final static int DATA_OK = 1;   //数据准备完成

    private UserInfo userInfo;              //用户数据

    private int userId = 0;                //用户ID


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Bundle bundle = getIntent().getExtras();
        if (bundle == null || !bundle.containsKey("userId")) {
            finish();
        }

        userId = bundle.getInt("userId");
        if (userId == AppContext.getInstance().getUserId()) {
            UIHelper.showActivityAndFinish(UserInfoActivity.this, UserCenterActivity.class);
            return;
        }

        setContentView(R.layout.activity_user_info);
        userService = new UserServiceImpl();

        initHead();
        initView();
        initListeners();
    }

    @Override
    public void onResume() {
        super.onResume();
        loadData();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DATA_OK:
                    tvName.setText(userInfo.getNickname());
                    int g = userInfo.getGrade();
                    tvLevel.setText(g == 8 ? "认证合伙人" : g == 0 ? "普通合伙人" : "优秀合伙人");
                    tvAttention.setText(userInfo.getAttention() + "人关注");
                    Picasso.with(UserInfoActivity.this)
                            .load(userInfo.getHead_pic())
                            .placeholder(R.mipmap.head_default)
                            .into(ivHead);
                    break;
            }
        }
    };

    /**
     * 加载个人信息数据
     */
    private void loadData() {

        ThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                userInfo = userService.getUserInfo(userId);
                if (userInfo != null) {
                    handler.sendEmptyMessage(DATA_OK);
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            UIHelper.ToastMessage(UserInfoActivity.this, "获取信息失败");
                            finish();
                        }
                    });
                }
            }
        });

    }

    /**
     * 初始化界面
     */
    private void initView() {
        llIdea = (LinearLayout) findViewById(R.id.ll_user_info_idea);
        llProject = (LinearLayout) findViewById(R.id.ll_user_info_project);
        llPartner = (LinearLayout) findViewById(R.id.ll_user_info_partner);
        llDetail = (LinearLayout) findViewById(R.id.ll_user_info_detail);
        llAddFriend = (LinearLayout) findViewById(R.id.ll_user_info_add_friend);
        llAddAtention = (LinearLayout) findViewById(R.id.ll_user_info_add_attention);
        ivHead = (CircleImageView) findViewById(R.id.ci_user_info_head);
        tvName = (TextView) findViewById(R.id.tv_user_info_name);
        tvAttention = (TextView) findViewById(R.id.tv_user_info_attention);
        tvLevel = (TextView) findViewById(R.id.tv_user_info_level);

        ivChat = (ImageView) findViewById(R.id.iv_chat);
    }

    /**
     * 初始化监听
     */
    private void initListeners() {
        llIdea.setOnClickListener(this);
        llProject.setOnClickListener(this);
        llPartner.setOnClickListener(this);
        llDetail.setOnClickListener(this);
        llAddFriend.setOnClickListener(this);
        llAddAtention.setOnClickListener(this);
        ivChat.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_user_info_idea:
                //他的想法
                if (userInfo == null) return;
                Bundle bundle1 = new Bundle();
                bundle1.putInt("userId", userId);
                bundle1.putString("userName", userInfo.getNickname());
                UIHelper.showActivity(UserInfoActivity.this, MyIdeasActivity.class, bundle1);
                break;
            case R.id.ll_user_info_project:
                //他的项目
                if (userInfo == null) return;
                Bundle bundle2 = new Bundle();
                bundle2.putInt("userId", userId);
                bundle2.putString("userName", userInfo.getNickname());
                UIHelper.showActivity(UserInfoActivity.this, MyProjectsActivity.class, bundle2);
                break;
            case R.id.ll_user_info_partner:
                //合伙人信息
                Bundle bundle3 = new Bundle();
                bundle3.putInt("userId", userId);
                UIHelper.showActivity(UserInfoActivity.this, PartnerInfoOtherActivity.class, bundle3);
                break;
            case R.id.ll_user_info_detail:
                if (userInfo != null) {
                    Intent intent = new Intent(UserInfoActivity.this, UserInfoDetailActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("userInfo", userInfo);
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
                //详细信息
                break;
            case R.id.ll_user_info_add_friend:
                //加好友
                if (!AppContext.getInstance().getIsLogined()) {
                    UIHelper.showNotLogined(UserInfoActivity.this);
                    return;
                }
                addContact();
                break;
            case R.id.ll_user_info_add_attention:
                //加关注
                if (!AppContext.getInstance().getIsLogined()) {
                    UIHelper.showNotLogined(UserInfoActivity.this);
                    return;
                }
                addAttention();
                break;
            case R.id.iv_chat:
                //对话
                Log.i("iv_chat", "clciked");
                if (userInfo != null) {
                    User user = UserUtils.getUserInfo(userId + "");
                    if (user == null) {
                        user = new User(userId + "");
                        user.setAvatar(userInfo.getHead_pic());
                        user.setNick(userInfo.getNickname());
                        UserUtils.saveUserInfo(user);
                    } else {
                        boolean c = false;
                        if (!user.getAvatar().equals(userInfo.getHead_pic())) {
                            c = true;
                            user.setAvatar(userInfo.getHead_pic());
                        }
                        if (!user.getNick().equals(userInfo.getNickname())) {
                            c = true;
                            user.setNick(userInfo.getNickname());
                        }
                        if (c) {
                            UserUtils.saveUserInfo(user);
                        }
                    }
                    Intent intent = new Intent(UserInfoActivity.this, ChatActivity.class);
                    intent.putExtra(ChatActivity.CHAT_TO_ID, userId);
                    intent.putExtra(ChatActivity.CHAT_TO_NAME, userInfo.getNickname());
                    startActivity(intent);
                } else {
                    Toast.makeText(UserInfoActivity.this, "请先登录!", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    private String temp = "请求加为好友";

    /**
     * 添加contact
     *
     * @param
     */
    public void addContact() {
        if (userInfo == null) return;

        final String username = userInfo.getNickname();

        if (AppContext.getInstance().getUserInfo().getNickname().equals(username)) {
            String str = "不能添加自己";
            UIHelper.ToastMessage(UserInfoActivity.this, str);
            return;
        }

        if (((DemoHXSDKHelper) HXSDKHelper.getInstance()).getContactList() != null && ((DemoHXSDKHelper) HXSDKHelper.getInstance()).getContactList().containsKey(username)) {
            //提示已在好友列表中，无需添加
            UIHelper.ToastMessage(UserInfoActivity.this, "此用户已经是你的好友");
            return;
        }

        final EditAlertDialog editAlertDialog = new EditAlertDialog(UserInfoActivity.this);
        editAlertDialog.setHint("请验证身份");
        editAlertDialog.setOnFinishedListener(new EditAlertDialog.OnFinishedListener() {
            @Override
            public void finish(String input) {
                if (!TextUtils.isEmpty(input)) {
                    temp = input;

                    final ProgressDialog progressDialog = new ProgressDialog(UserInfoActivity.this);
                    String stri = "已发送";
                    progressDialog.setMessage(stri);
                    progressDialog.setCanceledOnTouchOutside(false);
                    progressDialog.show();

                    new Thread(new Runnable() {
                        public void run() {

                            try {
                                EMContactManager.getInstance().addContact(username, temp);
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                        progressDialog.dismiss();
                                        String s1 = "发送成功";
                                        UIHelper.ToastMessage(UserInfoActivity.this, s1);
                                    }
                                });
                            } catch (final Exception e) {
                                e.printStackTrace();
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                        progressDialog.dismiss();
                                        UIHelper.ToastMessage(UserInfoActivity.this, "发送失败");
                                    }
                                });
                            }
                        }
                    }).start();
                }
            }
        });
    }

    /**
     * 加关注
     */
    private void addAttention() {

        final AlertDialog ad = new AlertDialog(UserInfoActivity.this);
        ad.setTitle("关注用户");
        ad.setMessage("确认关注该用户？");
        ad.setPositiveButton("确认", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ThreadPoolUtils.execute(new Runnable() {
                    @Override
                    public void run() {
                        final boolean result = userService.attention(userId, true);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (result) {
                                    UIHelper.ToastMessage(UserInfoActivity.this, "关注成功");
                                } else {
                                    UIHelper.ToastMessage(UserInfoActivity.this, "您已关注该用户");
                                }
                            }
                        });

                    }
                });
                ad.dismiss();
            }
        });
        ad.setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ad.dismiss();
            }
        });


    }
}
